package com.su.utils;

/**
 * @author ihaokun
 * @date 2019/12/16 9:42
 */
public class ByteUtils {
  public static byte[] hexStringToBytes(String hexString) {
    if (hexString != null && !hexString.equals("")) {
      hexString = hexString.toUpperCase();
      int length = hexString.length() / 2;
      char[] hexChars = hexString.toCharArray();
      byte[] d = new byte[length];

      for(int i = 0; i < length; ++i) {
        int pos = i * 2;
        d[i] = (byte)(charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
      }

      return d;
    } else {
      return null;
    }
  }
  private static byte charToByte(char c) {
    return (byte)"0123456789ABCDEF".indexOf(c);
  }
  public static String toHexString(byte[] b) {
    StringBuffer buffer = new StringBuffer();

    for (byte value : b) {
      buffer.append(toHexString1(value));
    }
    return buffer.toString();
  }
  public static String toHexString1(byte b) {
    String s = Integer.toHexString(b & 255);
    return s.length() == 1 ? "0" + s : s;
  }
}